<?php

namespace app\api\controller;

use app\api\library\CacheCart;
use app\common\controller\Api;
use app\common\model\Collect;
use app\common\model\mall\Coupon;
use app\common\model\UserCoupon;
use think\Cache;
use think\Db;
use think\Exception;
use think\Log;

class Mall extends Api
{
    protected $noNeedRight = '*';
    /**
     * 记录搜索历史记录   缓存中可以存储数组
     * @return void
     * explode 把字符串打散为数组
     */
    public function addSearchLog(){
        $keywords = $this->request->post('keywords');
        if(empty($keywords)){
            $this->error(__('Parameter missing'));
        }
        if (empty($this->auth->id)) $this->error(__('Please login first'), null, 401);
        $key = 'SearchLog'.$this->auth->id;
        try {
            if(Cache::has($key)){
                $history = Cache::get($key);
                array_unshift($history, $keywords); //在数组开头插入一个或多个元素
                $history = array_unique($history);  //移除数组中的重复的值，并返回结果数组。
                if(count($history) > 10){
                    array_pop($history);  //  弹出数组最后一个单元（出栈）
                }
                Cache::set($key, $history, time() + 3600 * 24 * 30);
                Db::name('search')->where('user_id',$this->auth->id)->delete();
            }else{
                $history = [$keywords];
                Cache::set($key, $history, time() + 3600 * 24 * 30);
            }
            Db::name('search')->insert([
                'keywords'=>json_encode($history,JSON_UNESCAPED_UNICODE),
                'user_id' => $this->auth->id,
                'createtime' => time(),
                'updatetime' => time(),
            ]);
        }catch (Exception $e){
            Log::write('错误信息：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
        $this->success(__('success'));
    }

    /**
     * 取出搜索历史记录
     * @return void
     */
    public function searchLog(){
        try {
            if (empty($this->auth->id)) $this->error(__('Please login first'), null, 401);
            $key = 'SearchLog'.$this->auth->id;
            if (Cache::has($key)){
                $history = Cache::get($key);
            }else{
                $history = [];
                $json_str = Db::name('search')->where('user_id',$this->auth->id)->value('keywords');
                if($json_str){
                    $history = json_decode($json_str,true);
                    Cache::set($key, $history, time() + 3600 * 24 * 30);
                }
            }
            $this->success(__('success'),$history);
        }catch (Exception $e){
            Log::write('错误信息：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 删除搜索历史记录
     * @return void
     */
    public function delSearchLog(){
        try {
            if (empty($this->auth->id)) $this->error(__('Please login first'), null, 401);
            $key = 'SearchLog'.$this->auth->id;
            Cache::rm($key);
            Db::name('search')->where('user_id',$this->auth->id)->delete();
            $this->success(__('success'));
        }catch (Exception $e){
            Log::write('错误信息：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 收藏
     * @return void
     */
    public function collect()
    {
        try {
            $id = $this->request->post('id/d');
            $type = $this->request->post('type');  //  类型:10=商家,20=商品
            if(empty($id) || empty($type) || !in_array($type,['10','20'])){
                $this->error(__('Invalid parameters'));
            }
            $model = new Collect();
            $row = $model->where(['user_id'=>['=',$this->auth->id],'type'=>['=',$type],'data_id'=>['=',$id]])->find();
            if($row){
                $result = $row->delete();
                $resStatus = false;
            }else{
                $result = $model->save(['user_id'=>$this->auth->id,'type'=>$type,'data_id'=>$id]);
                $resStatus = true;
            }
            if($result === false){
                $this->error(__('Operation failed'));
            }
            $this->success(__('Operation completed'),$resStatus);
        }catch (Exception $e){
            Log::write('错误信息：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 领取优惠券
     * @return void
     */
    public function obtain(){
        try {
            $coupon_id = $this->request->post('coupon_id/d');
            if(empty($coupon_id)){
                $this->error(__('Parameter error'));
            }
            $couponTmp = Coupon::where([
                'id'=>['=',$coupon_id],
                'switch' => ['=',1],
                'starttime'=>['<=',time()],
                'endtime'=>['>',time()]
            ])->find();
            if(empty($couponTmp)){
                $this->error(__('Parameter error'));
            }
            //用户领取记录
            $tempNum = UserCoupon::where(['user_id' => [ '=' , $this->auth->id ],'coupon_id' => [ '=' , $coupon_id ] ])->count();
            if($tempNum){
                $tmp = UserCoupon::where(['user_id' => [ '=' , $this->auth->id ],'coupon_id' => [ '=' , $coupon_id ] ])->order('id desc')->find();
                if($tmp && (!$tmp['use_switch'])){
                    throw new Exception(__('已领取，尚未使用'));
                }
                if($couponTmp['num'] && ($tempNum >= $couponTmp['num']) ){
                    throw new Exception(__('已使用，不可再次领取'));
                }
            }
            $res = UserCoupon::create([
                'user_id' => $this->auth->id,
                'coupon_id' => $coupon_id,
                'title' => $couponTmp['title'],
                'modality' => $couponTmp['modality'],
                'threshold_value' => $couponTmp['threshold_value'],
                'quantity' => $couponTmp['quantity'],
                'gittime' => time(),
                'starttime' => $couponTmp['starttime'],
                'endtime' => $couponTmp['endtime'],
            ]);
            $this->success(__('success'),['id'=>$res->id]);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 添加购物车
     * @return void
     * @throws \think\exception\DbException
     */
    public function addCart(){
        $goods_id = $this->request->post('goods_id/d');  //商品ID
        $goods_sku_id = $this->request->post('goods_sku_id');  //规格ID
        $num = $this->request->post('num/d');
        if(empty($goods_id) || empty($goods_sku_id) || empty($num)){
            $this->error(__('Parameter missing'));
        }
        $cartModel = new CacheCart($this->auth->id);
        $result = $cartModel->add($goods_id,$goods_sku_id,$num);
        if($result === false){
            $this->error($cartModel->getError());
        }
        $this->success(__('success'));
    }

    /**
     * 增加购物车
     * @return void
     */
    public function inc(){
        $goods_id = $this->request->post('goods_id/d');  //商品ID
        $goods_sku_id = $this->request->post('goods_sku_id');  //规格ID
        if(empty($goods_id) || empty($goods_sku_id)){
            $this->error(__('Parameter missing'));
        }
        $cartModel = new CacheCart($this->auth->id);
        $result = $cartModel->inc($goods_id,$goods_sku_id);
        if($result === false){
            $this->error($cartModel->getError());
        }
        $this->success(__('success'));
    }

    /**
     * 减少购物车
     * @return void
     */
    public function sub(){
        $goods_id = $this->request->post('goods_id/d');  //商品ID
        $goods_sku_id = $this->request->post('goods_sku_id');  //规格ID
        if(empty($goods_id) || empty($goods_sku_id)){
            $this->error(__('Parameter missing'));
        }
        $cartModel = new CacheCart($this->auth->id);
        $result = $cartModel->sub($goods_id,$goods_sku_id);
        if($result === false){
            $this->error($cartModel->getError());
        }
        $this->success(__('success'));
    }

    /**
     * 删除购物车
     * @return void
     */
    public function del(){
        $keyStr = $this->request->post('str');   //购物车列表  key  逗号拼接
        if(!$keyStr){
            $this->error(__('Parameter missing'));
        }
        $keyArr = explode(',',$keyStr);
        if($keyArr){
            foreach ($keyArr as $k=>$v){
                list($goods_id,$goods_sku_id) = explode('_',$v);
                /*$goods_id = $this->request->post('goods_id/d');  //商品ID
                $goods_sku_id = $this->request->post('goods_sku_id/d');  //规格ID
                if(empty($goods_id) || empty($goods_sku_id)){
                    $this->error('参数缺失');
                }*/
                $cartModel = new CacheCart($this->auth->id);
                $result = $cartModel->del($goods_id,$goods_sku_id);
                if($result === false){
                    $this->error($cartModel->getError());
                }
            }
        }
        $this->success(__('success'));
    }

    /**
     * 购物车列表
     * @return void
     */
    public function cartList(){
        $cartModel = new CacheCart($this->auth->id);
        $result = $cartModel->getList();
        if($result === false){
            $this->error($cartModel->getError());
        }
        $this->success(__('success'),$result);
    }

}